package compress;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;




import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class ZipUtil {

	public  static void main(String args[]){

		String f1 = "src/file/Java编码规范.doc";
		String f2 = "src/file/ibatis 开发指南.pdf";
		String zip = "src/张奇.zip";
		List<String> f = new ArrayList<String>();
		f.add(f1);
		f.add(f2);
		zipFiles(f,zip);
	}

    /** 
     * 功能:压缩多个文件成一个zip文件 
     * @param srcfile：源文件列表 
     * @param zipfile：压缩后的文件 
     */  
    @SuppressWarnings("rawtypes")
	public static boolean zipFiles(List srcfile,String zipfile){  
        boolean reFlag = false;
        byte[] buf=new byte[10240];  
        ZipOutputStream out = null;
        FileInputStream in = null;
        try {  
            //ZipOutputStream类：完成文件或文件夹的压缩  
        	File zipFile = new File(zipfile);
            out=new ZipOutputStream(new FileOutputStream(zipFile));  
            //注意此处编码设置
            out.setEncoding("gbk");
            for(int i=0;i<srcfile.size();i++){
            	File file = new File((String) srcfile.get(i));
                in=new FileInputStream(file);  
                out.putNextEntry(new ZipEntry(file.getName()));  
                int len;  
                while((len=in.read(buf))>0){  
                    out.write(buf,0,len);  
                }  
                out.closeEntry();  
                in.close();  
                in = null;
            }  
            out.close();  
            out = null;
            reFlag = true;

        } catch (Exception e) {  
        	System.out.println("error");
            e.printStackTrace();  
        } finally{
            if(in!=null){
                try {
                    in.close();
                    in = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){
                try {
                    out.close();
                    out = null;
                    System.err.println("压缩文件完成！");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } 
        return reFlag;
    }  
  }
